<template>
  <div>
    <div class="card" style="margin-bottom: 5px">
      <el-input v-model="data.circleName" prefix-icon="Search" style="width: 240px; margin-right: 10px" placeholder="请输入圈子名称查询"></el-input>
      <el-button type="info" plain @click="load">查询</el-button>
      <el-button type="warning" plain style="margin: 0 10px" @click="reset">重置</el-button>
    </div>
    <div class="card" style="margin-bottom: 5px">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>

    <div class="card" style="margin-bottom: 5px">
      <el-table
          stripe
          :data="data.tableData"
          @selection-change="handleSelectionChange"
          row-key="id"
          :tree-props="{ children: 'children' }"
          :row-class-name="rowClassName">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="circleName" label="圈子名称">
          <template v-slot="scope">
            <span style="cursor: pointer; color: #409EFF">
              {{ scope.row.circleName }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="icon" label="图标" width="150">
          <template v-slot="scope">
            <img v-if="scope.row.icon" :src="scope.row.icon" alt="分类图片" style="width: 100px; height: 100px; object-fit: cover;" />
            <span v-else>暂无图片</span>
          </template>
        </el-table-column>
        <el-table-column prop="createUsername" label="创建者" />
        <el-table-column prop="updateUsername" label="更新者" />
        <el-table-column prop="createdAt" label="创建时间" />
        <el-table-column prop="updatedAt" label="更新时间" />
        <el-table-column label="操作" width="100" fixed="right">
          <template v-slot="scope">
            <el-button type="primary" circle :icon="Edit" @click="handleEdit(scope.row)"></el-button>
            <el-button type="danger" circle :icon="Delete" @click="del(scope.row.id)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="card" v-if="data.total">
      <el-pagination @current-change="load" background layout="prev, pager, next" :page-size="data.pageSize" v-model:current-page="data.pageNum" :total="data.total" />
    </div>

    <!-- 弹窗部分 -->
    <el-dialog title="圈子信息" v-model="data.formVisible" width="40%" destroy-on-close>
      <el-form ref="form" :model="data.form" label-width="70px" style="padding: 20px">
        <el-form-item prop="circleName" label="圈子名称">
          <el-input v-model="data.form.circleName" placeholder="请输入圈子名称"></el-input>
        </el-form-item>
        <el-form-item prop="icon" label="图标URL">
          <el-input v-model="data.form.icon" placeholder="请输入图标URL"></el-input>
        </el-form-item>
        <el-form-item label="父类">
          <el-select v-model="data.form.parentId" placeholder="请选择父类" clearable>
            <el-option v-for="item in data.parentOptions" :key="item.id" :label="item.circleName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建者">
          <el-input v-model="data.form.createUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新者">
          <el-input v-model="data.form.updateUsername" disabled></el-input>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-input v-model="data.form.createdAt" disabled></el-input>
        </el-form-item>
        <el-form-item label="更新时间">
          <el-input v-model="data.form.updatedAt" disabled></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="data.formVisible = false">取 消</el-button>
          <el-button type="primary" @click="save">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive } from "vue";
import request from "@/utils/request.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Edit } from "@element-plus/icons-vue";

const data = reactive({
  formVisible: false,
  form: {},
  tableData: [],
  pageNum: 1,
  pageSize: 10,
  total: 0,
  circleName: null,
  ids: [],
  parentOptions: []
});

const rowClassName = ({ row }) => {
  return row.parentId !== -1 ? 'child-row' : 'parent-row';
};

const load = () => {
  request.get('/circle/share/circle/list', {
    params: {
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      circleName: data.circleName
    }
  }).then(res => {
    if (res.code === '200') {
      data.tableData = res.data || [];
      console.log('data.tableData', data.tableData);
      // 提取所有顶级分类作为父类选项
      extractParentOptions(data.tableData);
    }
  });
};

const extractParentOptions = (tableData) => {
  const allIds = new Set();
  const childIds = new Set();

  // 收集所有子节点的ID
  const collectChildIds = (items) => {
    items.forEach(item => {
      if (item.children && item.children.length > 0) {
        item.children.forEach(child => {
          childIds.add(child.id);
          collectChildIds(child.children);
        });
      }
    });
  };

  collectChildIds(tableData);

  // 收集所有节点的ID
  const collectAllIds = (items) => {
    items.forEach(item => {
      allIds.add(item.id);
      collectAllIds(item.children);
    });
  };

  collectAllIds(tableData);

  // 计算顶级分类（不在子节点集合中的节点）
  const parents = Array.from(allIds).filter(id => !childIds.has(id)).map(id => {
    const item = findItemById(tableData, id);
    return { id: item.id, circleName: item.circleName };
  });

  data.parentOptions = [{ id: -1, circleName: '无父类' }, ...parents];
};

const findItemById = (items, id) => {
  for (const item of items) {
    if (item.id === id) {
      return item;
    }
    if (item.children && item.children.length > 0) {
      const found = findItemById(item.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

// 新增
const handleAdd = () => {
  data.form = {};
  data.form.parentId = -1; // 初始化父类ID为-1表示顶级分类
  data.formVisible = true;
};

// 编辑
const handleEdit = (row) => {
  data.form = JSON.parse(JSON.stringify(row));
  data.form.parentId = row.parentId !== undefined ? row.parentId : -1; // 确保 parentId 存在且有值
  data.formVisible = true;
};

// 保存操作
const save = () => {
  data.form.id ? update() : add();
};

// 添加操作
const add = () => {
  request.post('/circle/share/circle/save', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 更新操作
const update = () => {
  request.put('/circle/share/circle/update', data.form).then(res => {
    if (res.code === '200') {
      ElMessage.success('操作成功');
      data.formVisible = false;
      load();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 删除操作
const del = (id) => {
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete('/circle/share/circle/remove', {data: {id}}).then(res => {
      if (res.code === '200') {
        ElMessage.success("删除成功");
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 批量删除
const delBatch = () => {
  if (!data.ids.length) {
    ElMessage.warning("请选择数据");
    return;
  }
  ElMessageBox.confirm('删除后数据无法恢复，您确定删除吗？', '删除确认', {type: 'warning'}).then(res => {
    request.delete("/circle/share/circle/remove", {data: {ids: data.ids}}).then(res => {
      if (res.code === '200') {
        ElMessage.success('操作成功');
        load();
      } else {
        ElMessage.error(res.msg);
      }
    });
  }).catch(err => {
    console.error(err);
  });
};

// 选择框变更时
const handleSelectionChange = (rows) => {
  data.ids = rows.map(v => v.id);
};

// 重置查询
const reset = () => {
  data.circleName = null;
  load();
};
load();
</script>

<style scoped>
.parent-row {
  background: #f8f8f9;
}

.child-row td:first-child .cell {
  padding-left: 40px !important;
}

:deep(.el-table__expand-icon) {
  cursor: pointer;
}

/* 设置图片固定大小并缩放 */
.el-table .el-table-column img {
  width: 100px;
  height: 100px;
  object-fit: cover;
}
</style>
